package common

import (
	"gin/model"
	"time"

	"github.com/dgrijalva/jwt-go/v4"
)

var jwtKey = []byte("licongcong@12")

type MyClaims struct {
	UserId uint
	jwt.StandardClaims
}

func ReleaseToken(user model.User) (string, error) {
	expireTime := jwt.NewTime(float64(time.Now().Unix()) + 86400) //有效期1天
	claims := MyClaims{
		UserId: user.ID,
		StandardClaims: jwt.StandardClaims{
			ExpiresAt: expireTime,   //失效时间
			IssuedAt:  jwt.Now(),    //token发放时间
			Issuer:    "licongcong", //谁发放的token/golang.org/x/tools/internal/typesinternal
			Subject:   "token",      //主题
		},
	}
	token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
	tokenString, err := token.SignedString(jwtKey)
	if err != nil {
		return "", err
	}
	return "licc " + tokenString, nil
}

func ParseToken(tokenString string) (*jwt.Token, *MyClaims, error) {
	Claims := &MyClaims{}
	token, err := jwt.ParseWithClaims(tokenString, Claims, func(token *jwt.Token) (interface{}, error) {
		return jwtKey, nil
	})

	return token, Claims, err
}
